package com.woniuxy.service.controller;

import com.aliyun.oss.OSSClient;
import com.woniuxy.commons.util.ResponseResult;
import com.woniuxy.commons.util.ResultStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.UUID;

@RestController
@RequestMapping("/oos")
//@CrossOrigin
public class FileController {
    // 注入阿里云客户端对象
    @Resource
    private OSSClient ossClient;

    // 指定桶的名字
    private static final String BUCKET_NAME = "xielaoban1997";

    // 指定文件url的前缀
    private static final String BASE_URL = "https://xielaoban1997.oss-cn-chengdu.aliyuncs.com/";

    @PostMapping("/upload/{type}/{item}")
    public ResponseResult upload(MultipartFile[] files, @PathVariable("type") String type, @PathVariable("item") String item){
        //保存文件路径的集合
        ArrayList<String> pathArr = new ArrayList<>();

        for (MultipartFile file : files) {
            //1.获得文件名字
            String originalFileName = file.getOriginalFilename();
            String finalFilename = type + "/" + item + "/"
                    //重新生成新的文件名
                    + UUID.randomUUID().toString().replace("-","")
                    //获取后缀文件名
                    + originalFileName.substring(originalFileName.lastIndexOf("."));

            //2.获取文件流
            InputStream inputStream = null;
            try {
                inputStream = file.getInputStream();
                //
                ossClient.putObject(
                        BUCKET_NAME,
                        finalFilename,
                        inputStream);

                /*//设置文件有效期  60天
                Date date = new Date(new Date().getTime() + 1000*3600*24*60);
                //获取url
                URL url = ossClient.generatePresignedUrl(BUCKET_NAME,
                        finalFilename,
                        date);*/

                //添加到集合中
                pathArr.add(BASE_URL + finalFilename);
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        //返回数据
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(200);
        responseResult.setStatus(ResultStatus.SUCCESS);
        responseResult.setMsg("上传成功");
        responseResult.setData(pathArr);
        return responseResult;
    }

}
